package com.wzw.wx.api.tools;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * PDF文件转图片
 *
 * @auth 吴泽稳 2023-03-09
 */
public class PDF2Png implements OfficeTransUtil {
    public void execute(String sourcePath) {

//        File file = new File("d:\\office\\1678236734904.pdf");
        File file = new File(sourcePath);
        String path = file.getAbsolutePath();
        String targetPathNoExt = path.substring(0, path.lastIndexOf("."));
//        File targetFile = new File("d:\\office\\pdfbox_image.png");
        try {
            PDDocument doc = Loader.loadPDF(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            int pageCount = doc.getNumberOfPages();
            for (int i = 0; i < pageCount; i++) {
                System.out.println("当前页面" + (i + 1));
                BufferedImage image = renderer.renderImageWithDPI(i, 296);
                //          BufferedImage image = renderer.renderImage(i, 2.5f);
                ImageIO.write(image, "PNG", new File(targetPathNoExt + "_" + i + ".png"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String executeInputStream(InputStream fileInput) throws Exception{

//        File file = new File("d:\\office\\1678236734904.pdf");
//        File file = new File(sourcePath);
//        String path = file.getAbsolutePath();
//        String targetPathNoExt = path.substring(0, path.lastIndexOf("."));
//        File targetFile = new File("d:\\office\\pdfbox_image.png");

        PDDocument doc = Loader.loadPDF(fileInput);
        PDFRenderer renderer = new PDFRenderer(doc);
        int pageCount = doc.getNumberOfPages();
        StringBuilder pathSB = new StringBuilder();
        for (int i = 0; i < pageCount; i++) {
            File file = new File(new Date().getTime() + "_" + i + ".png");
            System.out.println("当前页面" + (i + 1));
            BufferedImage image = renderer.renderImageWithDPI(i, 296);
            //          BufferedImage image = renderer.renderImage(i, 2.5f);
            ImageIO.write(image, "PNG", file);
            pathSB.append(file.getAbsolutePath()+",");
            System.out.println("filePath = " + file.getAbsolutePath());
        }
        return pathSB.deleteCharAt(pathSB.lastIndexOf(",")).toString();
    }
}
